package config

import (
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"log"
)

func InitViperByStruct(configFile string, stu interface{}) {
	v := viper.New()
	v.SetConfigFile(configFile)

	err := v.ReadInConfig()
	if err != nil {
		log.Panic("读取配置文件失败", err)
		return
	}
	err = v.Unmarshal(&stu)
	if err != nil {
		log.Panic("解析配置文件失败", err)
		return
	}

	v.WatchConfig()
	//动态监听

	v.OnConfigChange(func(c fsnotify.Event) {
		err = v.Unmarshal(&stu)
		if err != nil {
			return
		}
		log.Println("本地配置文件发生变动", err)
	})
	log.Println("viper初始化完成")
	log.Println(stu)

	return
}
